package com.lixinwen.gdgame.websocket.endpoint;

import com.lixinwen.gdgame.game.RoomManager;
import com.lixinwen.gdgame.vo.RoomVo;
import io.netty.handler.codec.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@ServerEndpoint(path="/msg",port = "30000")
public class MyWebSocket {

    private RoomManager roomManager = new RoomManager();

    @BeforeHandshake
    public void beforeHandshake(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
        System.out.println("handShake");
    }

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
        roomManager.handleNewConn(session,getFromRequest(reqMap));
        System.out.println("new connection");
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("one connection closed");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void OnMessage(Session session, String message) {
        System.out.println(message);
        roomManager.handleMessage(session,message);
        session.sendText("Hello Netty!");
    }

    RoomVo getFromRequest(MultiValueMap reqMap){
        return new RoomVo(((List<String>)reqMap.get("room")).get(0),((List<String>)reqMap.get("seat")).get(0));
    }
}


